import {defineStore} from 'pinia'
import {getInfo, loginUrl, logout} from "@/api/login.ts";
import {LoginBody, LoginResponse} from "@/types/login.ts";
import {getExpiresIn, getToken, removeExpiresIn, removeToken, setExpiresIn, setToken} from "@/utils/auth.ts";
// import cache from "@/plugins/cache.ts";
import defAvatar from '@/assets/images/notlogin.png'

const useUserStore = defineStore('user', {
    state: () => ({
        token: getToken(), // token
        expiresIn: getExpiresIn(), // 过期时间
        userInfo: {}, // 用户信息
        isLogin: false, // 是否登录
        id: '',
        name: '',
        avatar: '',
        roles: [],
    }),
    getters: {},
    actions: {
        // 异步登录获取 token
        login(data: LoginBody) {
            return new Promise((resolve, reject) => {
                loginUrl(data).then((res: LoginResponse) => {
                    this.token = res.data.access_token
                    this.expiresIn = res.data.expires_in
                    setToken(res.data.access_token)
                    setExpiresIn(res.data.expires_in)
                    // 将其保存到会话中
                    this.isLogin = true
                    resolve(res)
                }).catch((error) => {
                    reject(error)
                })
            })
        },
        // 获取用户信息
        getInfo() {
            return new Promise((resolve, reject) => {
                getInfo().then(res => {
                    const user = res.user
                    const avatar = (user.avatar == "" || user.avatar == null) ? defAvatar : user.avatar;
                    this.id = user.userId
                    this.name = user.userName
                    this.avatar = avatar
                    this.isLogin = true
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 退出登录
        logOut() {
            // 清除所有的与登录有关的信息
            return new Promise((resolve, reject) => {
                logout(this.token).then(() => {
                    this.token = ''
                    removeToken()
                    // 清除过期时间
                    removeExpiresIn()
                    // 清除用户信息
                    this.isLogin = false
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        }
    },
})

export default useUserStore
